﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EM.Repository.utility;
using System.Data.SqlClient;
using System.Data;
using Telerik.WebControls;

namespace EM.definition.finance.ExchangeRates
{
    public partial class _default : System.Web.UI.Page
    {
        string APPROOT = "";
        int PageId = 32;
        int count = 0;
        int startPageNumber = 0;
        public int CurrentPage
        {
            get
            {
                object o = this.ViewState["_CurrentPage"];
                if (o == null)
                    return 0; // default page index of 0
                else
                    return (int)o;
            }
            set
            {
                this.ViewState["_CurrentPage"] = value;
            }
        }

       

        protected void Page_Load(object sender, EventArgs e)
        {
            AppPathFinder AppPath = new AppPathFinder();
            APPROOT = AppPath.GetApplicationPath();

            Authentication Rua = new Authentication();
            Rua.CheckRolePageAuthentication(PageId, Authentication.RedirectionURLTypes.LoginPage);

            if (!IsPostBack)
            {
                FillCombo fc = new FillCombo();
                fc.Currency(ddlCurrencyCode, "0", true);

                rdpStartDate.SelectedDate = DateTime.Now.Date;
                rdpEndDate.SelectedDate = DateTime.Now.Date;
                sharedCalendar.Visible = false;

                getdata();
            }
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            getdata();
        }

        private void getdata()
        {
            string sSQL = "";
            SqlCommand cmd = new SqlCommand();
            sSQL += @"  SELECT EXCHANGERATEID, C.CURRENCYID, CURRENCYNAME, CONVERT(NVARCHAR,EXCHANGEDATE,104) AS EXCHANGEDATE, PURCHASERATE, SALESRATE, EFFECTIVESALES, EFFECTIVEPURCHASE
                        FROM TBLEXCHANGERATE R, TBLCURRENCY C
                        WHERE 1 = 1
                        AND R.CURRENCYID = C.CURRENCYID AND R.WORKGROUPID = " + Session["WORKGROUPID"];

            if (ddlCurrencyCode.SelectedValue != "0" && ddlCurrencyCode.SelectedValue != "")
            {
                sSQL += " AND R.CURRENCYID = @CURRENCYID ";
                cmd.Parameters.AddWithValue("CURRENCYID", ddlCurrencyCode.SelectedValue);
            }
            DateTime cal = new DateTime(2000, 01, 01);

            if (rdpStartDate.SelectedDate != cal)
            {
                sSQL += " AND R.EXCHANGEDATE >= @STARTDATE";
                cmd.Parameters.AddWithValue("STARTDATE", rdpStartDate.SelectedDate);
            }
            if (rdpEndDate.SelectedDate != cal)
            {
                sSQL += " AND R.EXCHANGEDATE <= @ENDDATE";
                cmd.Parameters.AddWithValue("ENDDATE", rdpEndDate.SelectedDate);
            }
            sSQL += " ORDER BY R.EXCHANGEDATE DESC, CURRENCYNAME";

            cmd.CommandText = sSQL;
            DbHelper srv = new DbHelper();
            DataTable dt = srv.GetDataTable(cmd, "TBLEXCHANGERATE");

            PagedDataSource pds = new PagedDataSource();
            pds.DataSource = dt.DefaultView;
            pds.PageSize = 20;
            pds.AllowPaging = true;
            pds.CurrentPageIndex = CurrentPage;

            drExchahngeRate.DataSource = pds;
            drExchahngeRate.DataBind();


            DataTable dtPager = new DataTable();
            DataColumn dc = new DataColumn();
            dc.ColumnName = "page";
            dtPager.Columns.Add(dc);

            if (pds.PageCount >= 10)
            {
                int _decimal = pds.PageCount / 10;
                int mod = pds.PageCount % 10;
                int pageAdd = 11;
                startPageNumber = Convert.ToInt32(CurrentPage / 10) * 10;

                if (_decimal > 0)
                {
                    if (startPageNumber > 9)
                    {
                        if (pds.PageCount - startPageNumber > 9)
                        {
                            pageAdd = 11;
                        }
                        else
                        {
                            pageAdd = mod;
                        }
                    }
                    else
                    {
                        pageAdd = 11;
                    }
                }
                else
                {
                    pageAdd = mod;
                }

                for (int i = startPageNumber; i <= startPageNumber + pageAdd; i++)
                {
                    dtPager.Rows.Add(i);
                }
            }
            else
            {
                startPageNumber = Convert.ToInt32(CurrentPage / 10) * 10;
                for (int i = startPageNumber; i <= pds.PageCount; i++)
                {
                    if (pds.PageCount > 1)
                        dtPager.Rows.Add(i);
                }
            }

            drPages.DataSource = dtPager;
            drPages.DataBind();
        }

        protected void drExchahngeRate_ItemdDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                FillCombo Fc = new FillCombo();
                DropDownList ddlCURRENCYID = (DropDownList)e.Item.FindControl("ddlCURRENCYID");

                RadDatePicker rdpEXCHANGEDATE = (RadDatePicker)e.Item.FindControl("rdpEXCHANGEDATE");
                Fc.Currency(ddlCURRENCYID, "1", true);
                rdpEXCHANGEDATE.SelectedDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
            }
            else if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DateTime date = Convert.ToDateTime(((DataRowView)e.Item.DataItem).Row["EXCHANGEDATE"].ToString());

                TextBox txtPURCHASERATE = ((TextBox)e.Item.FindControl("txtPURCHASERATE"));
                TextBox txtSALESRATE = ((TextBox)e.Item.FindControl("txtSALESRATE"));


                TextBox txtEFFECTIVESALES = ((TextBox)e.Item.FindControl("txtEFFECTIVESALES"));
                TextBox txtEFFECTIVEPURCHASE = ((TextBox)e.Item.FindControl("txtEFFECTIVEPURCHASE"));



                FillCombo Fc = new FillCombo();
                LinkButton btnUpdate = ((LinkButton)e.Item.FindControl("btnUpdate"));
                LinkButton btnDelete = ((LinkButton)e.Item.FindControl("btnDelete"));
                TextBox txtEXCHANGEDATE = (TextBox)e.Item.FindControl("txtEXCHANGEDATE");

                RadCalendar sharedCalendar = ((RadCalendar)e.Item.FindControl("sharedCalendar"));

                RequiredFieldValidator rfvEXCHANGEDATE = (RequiredFieldValidator)e.Item.FindControl("rfvEXCHANGEDATE");
                RequiredFieldValidator rfvPURCHASERATE = (RequiredFieldValidator)e.Item.FindControl("rfvPURCHASERATE");
                RequiredFieldValidator rfvSALESRATE = (RequiredFieldValidator)e.Item.FindControl("rfvSALESRATE");
                RequiredFieldValidator rfvEFFECTIVEPURCHASE = (RequiredFieldValidator)e.Item.FindControl("rfvEFFECTIVEPURCHASE");
                RequiredFieldValidator rfvEFFECTIVESALES = (RequiredFieldValidator)e.Item.FindControl("rfvEFFECTIVESALES");
                RegularExpressionValidator revEXCHANGEDATE = (RegularExpressionValidator)e.Item.FindControl("revEXCHANGEDATE");
                ValidationSummary vsItem = (ValidationSummary)e.Item.FindControl("vsItem");
                HiddenField hfEXCHANGEDATE = (HiddenField)e.Item.FindControl("hfEXCHANGEDATE");

                Conversion oC = new Conversion();
                double PURCHASERATE = oC.CNumC2S(((DataRowView)e.Item.DataItem).Row["PURCHASERATE"].ToString(), 4);
                double SALESRATE = oC.CNumC2S(((DataRowView)e.Item.DataItem).Row["SALESRATE"].ToString(), 4);


                double EFFECTIVESALES = 0;
                double EFFECTIVEPURCHASE = 0;

                if (((DataRowView)e.Item.DataItem).Row["EFFECTIVESALES"].ToString() != "")
                    EFFECTIVESALES = oC.CNumC2S(((DataRowView)e.Item.DataItem).Row["EFFECTIVESALES"].ToString(), 4);
                if (((DataRowView)e.Item.DataItem).Row["EFFECTIVEPURCHASE"].ToString() != "")
                    EFFECTIVEPURCHASE = oC.CNumC2S(((DataRowView)e.Item.DataItem).Row["EFFECTIVEPURCHASE"].ToString(), 4);



                vsItem.ValidationGroup = rfvPURCHASERATE.ValidationGroup = rfvSALESRATE.ValidationGroup = rfvEXCHANGEDATE.ValidationGroup = revEXCHANGEDATE.ValidationGroup = btnUpdate.ValidationGroup = rfvEFFECTIVEPURCHASE.ValidationGroup = rfvEFFECTIVESALES.ValidationGroup = "vsf1" + e.Item.ItemIndex;

                txtEXCHANGEDATE.Text = hfEXCHANGEDATE.Value;
                txtPURCHASERATE.Text = PURCHASERATE.ToString();
                txtSALESRATE.Text = SALESRATE.ToString();

                txtEFFECTIVESALES.Text = EFFECTIVESALES.ToString();
                txtEFFECTIVEPURCHASE.Text = EFFECTIVEPURCHASE.ToString();


                btnDelete.OnClientClick = "javascript:return confirm('Silmek için devam etmek istiyor musunuz')";
                //HtmlImage imgInfo = (HtmlImage)e.Item.FindControl("imgInfo");
                //imgInfo.Attributes.Add("Title", "Kayıt Bilgileri");
            }
        }

        protected void drExchahngeRate_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            DbHelper srv = new DbHelper();
            Conversion oC = new Conversion();

            string CURRENCYID = "";
            string EXCHANGEDATE = "";
            double PURCHASERATE = oC.CNumC2S(((TextBox)e.Item.FindControl("txtPURCHASERATE")).Text.Trim(), 4);
            double SALESRATE = oC.CNumC2S(((TextBox)e.Item.FindControl("txtSALESRATE")).Text.Trim(), 4);
            double EFFECTIVESALES = 0;
            double EFFECTIVEPURCHASE = 0;
            if (((TextBox)e.Item.FindControl("txtEFFECTIVESALES")).Text.Trim() != "")
                EFFECTIVESALES = oC.CNumC2S(((TextBox)e.Item.FindControl("txtEFFECTIVESALES")).Text.Trim(), 4);

            if (((TextBox)e.Item.FindControl("txtEFFECTIVEPURCHASE")).Text.Trim() != "")
                EFFECTIVEPURCHASE = oC.CNumC2S(((TextBox)e.Item.FindControl("txtEFFECTIVEPURCHASE")).Text.Trim(), 4);



            if (e.CommandName == "Insert")
            {
                CURRENCYID = ((DropDownList)e.Item.FindControl("ddlCURRENCYID")).SelectedValue;
                EXCHANGEDATE = ((RadDatePicker)e.Item.FindControl("rdpEXCHANGEDATE")).SelectedDate.ToShortDateString();

                if (!isAlradyRate(CURRENCYID, "1", "D", EXCHANGEDATE, 0))
                {
                    SqlCommand cmd = new SqlCommand();
                    string sSQL = "";

                    sSQL += " INSERT INTO TBLEXCHANGERATE (CURRENCYID, RATETYPE, EXCHANGEDATE, PURCHASERATE, SALESRATE,  BASECURRENCYID, ";
                    sSQL += " CREUSERID, CREDATE, MODUSERID, MODDATE, EFFECTIVESALES, EFFECTIVEPURCHASE)";
                    sSQL += " SELECT @CURRENCYID, @RATETYPE, @EXCHANGEDATE, @PURCHASERATE, @SALESRATE,  @BASECURRENCYID,";
                    sSQL += " @CREUSERID, GETDATE(), @CREUSERID, GETDATE(), @EFFECTIVESALES, @EFFECTIVEPURCHASE";

                    cmd.Parameters.Add("CURRENCYID", SqlDbType.Int).Value = CURRENCYID;
                    cmd.Parameters.Add("BASECURRENCYID", SqlDbType.Int).Value = 1; //1->TL
                    cmd.Parameters.Add("RATETYPE", SqlDbType.NVarChar).Value = "D";
                    cmd.Parameters.Add("EXCHANGEDATE", SqlDbType.DateTime).Value = EXCHANGEDATE;
                    cmd.Parameters.Add("PURCHASERATE", SqlDbType.Float).Value = PURCHASERATE;
                    cmd.Parameters.Add("SALESRATE", SqlDbType.Float).Value = SALESRATE;

                    cmd.Parameters.Add("EFFECTIVESALES", SqlDbType.Float).Value = EFFECTIVESALES;
                    cmd.Parameters.Add("EFFECTIVEPURCHASE", SqlDbType.Float).Value = EFFECTIVEPURCHASE;


                    cmd.Parameters.Add("CREUSERID", SqlDbType.Int).Value = Session["USERID"].ToString();
                    cmd.Parameters.Add("MODUSERID", SqlDbType.Int).Value = Session["USERID"].ToString();
                    cmd.CommandText = sSQL;

                    srv.ExecuteNonQuery(cmd);
                    getdata();
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(typeof(string), "", "alert('')", true);
                }
            }
            else if (e.CommandName == "Update")
            {
                CURRENCYID = ((HiddenField)e.Item.FindControl("hdnCURRENCY")).Value;
                EXCHANGEDATE = ((TextBox)e.Item.FindControl("txtEXCHANGEDATE")).Text.Trim();
                string EXCHANGERATEID = e.CommandArgument.ToString();//((LinkButton)drExchahngeRate.Items[e.Item.ItemIndex].FindControl("btnUpdate")).CommandArgument;

                if (!isAlradyRate(CURRENCYID, "1", "D", EXCHANGEDATE, Convert.ToInt32(EXCHANGERATEID)))
                {
                    SqlCommand cmd = new SqlCommand();
                    string sSQL = "";

                    sSQL += " UPDATE TBLEXCHANGERATE SET";
                    sSQL += " EXCHANGEDATE = @EXCHANGEDATE,";
                    sSQL += " PURCHASERATE = @PURCHASERATE,";
                    sSQL += " SALESRATE = @SALESRATE,";
                    sSQL += " MODUSERID = @MODUSERID,";
                    sSQL += " MODDATE = GETDATE(),";
                    sSQL += " EFFECTIVESALES = @EFFECTIVESALES, ";
                    sSQL += " EFFECTIVEPURCHASE = @EFFECTIVEPURCHASE ";
                    sSQL += " WHERE EXCHANGERATEID = @EXCHANGERATEID";

                    cmd = new SqlCommand();
                    cmd.Parameters.Add("EXCHANGERATEID", SqlDbType.Int).Value = EXCHANGERATEID;
                    cmd.Parameters.Add("EXCHANGEDATE", SqlDbType.DateTime).Value = EXCHANGEDATE;
                    cmd.Parameters.Add("PURCHASERATE", SqlDbType.Float).Value = PURCHASERATE;
                    cmd.Parameters.Add("SALESRATE", SqlDbType.Float).Value = SALESRATE;
                    cmd.Parameters.Add("MODUSERID", SqlDbType.Int).Value = Session["USERID"].ToString();
                    cmd.Parameters.Add("EFFECTIVESALES", SqlDbType.Float).Value = EFFECTIVESALES;
                    cmd.Parameters.Add("EFFECTIVEPURCHASE", SqlDbType.Float).Value = EFFECTIVEPURCHASE;


                    cmd.CommandText = sSQL;

                    srv.ExecuteNonQuery(cmd);
                    getdata();
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(typeof(string), "", "alert('')", true);
                }
            }
            else if (e.CommandName == "Delete")
            {
                try
                {
                    string EXCHANGERATEID = e.CommandArgument.ToString(); //((LinkButton)drExchahngeRate.Items[e.Item.ItemIndex].FindControl("btnUpdate")).CommandArgument;

                    SqlCommand cmd = new SqlCommand();
                    string sSQL = "";

                    sSQL = " DELETE FROM TBLEXCHANGERATE WHERE EXCHANGERATEID = @EXCHANGERATEID";
                    cmd.Parameters.Add("EXCHANGERATEID", SqlDbType.Int).Value = EXCHANGERATEID;
                    cmd.CommandText = sSQL;

                    srv.ExecuteNonQuery(cmd);
                    getdata();
                }
                catch
                {

                }
            }



        }

        private bool isAlradyRate(string CURRENCYID, string BASECURRENCYID, string RATETYPE, string EXCHANGEDATE, int EXCHANGERATEID)
        {
            DbHelper Dsrv = new DbHelper();
            SqlCommand Cmd = new SqlCommand();
            string sSQL = "";
            bool Return = true;

            sSQL += " SELECT COUNT(*) ";
            sSQL += " FROM TBLEXCHANGERATE";
            sSQL += " WHERE 1 = 1";
            sSQL += " AND ((CURRENCYID = @CURRENCYID AND BASECURRENCYID = @BASECURRENCYID) ";
            sSQL += "       OR (CURRENCYID = @BASECURRENCYID AND BASECURRENCYID = @CURRENCYID))";
            sSQL += " AND RATETYPE = @RATETYPE";
            sSQL += " AND EXCHANGEDATE = @EXCHANGEDATE";
            if (EXCHANGERATEID > 0)
            {
                sSQL += " AND EXCHANGERATEID <> @EXCHANGERATEID";
            }

            Cmd.Parameters.Add("CURRENCYID", SqlDbType.Int).Value = CURRENCYID;
            Cmd.Parameters.Add("BASECURRENCYID", SqlDbType.Int).Value = BASECURRENCYID;
            Cmd.Parameters.Add("RATETYPE", SqlDbType.NVarChar).Value = "D";
            Cmd.Parameters.Add("EXCHANGEDATE", SqlDbType.DateTime).Value = EXCHANGEDATE;
            Cmd.Parameters.Add("EXCHANGERATEID", SqlDbType.Int).Value = EXCHANGERATEID;
            Cmd.CommandText = sSQL;
            int RecodCount = Convert.ToInt16(Dsrv.GetDataTable(Cmd, "TBLisAlradyRate").Rows[0][0]);

            if (RecodCount > 0)
            {
                Return = true;
            }
            else
            {
                Return = false;
            }

            return Return;
        }

        protected void drPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                int rowCount = ((DataTable)((DataView)((PagedDataSource)drExchahngeRate.DataSource).DataSource).ToTable()).Rows.Count;

                Label lblFooter = (Label)e.Item.FindControl("lblFooter");

                if (rowCount == 0)
                {
                    lblFooter.Text = "Kayıt bulunamadı";
                }
                else if (rowCount <= 20)
                {
                    lblFooter.Text = rowCount.ToString() + " adet kayıt bulundu.";
                }
                else
                {
                    lblFooter.Text = rowCount.ToString() + " adet kayıt bulundu." + " | Sayfaya git" + " : ";
                }
            }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton btnPage = (LinkButton)e.Item.FindControl("btnPage");
                Label lblPage = (Label)e.Item.FindControl("lblPage");
                int pageNumber = Convert.ToInt32(((DataRowView)e.Item.DataItem).Row["page"]);

                if (pageNumber == CurrentPage + 1)
                {
                    lblPage.Visible = true;
                    btnPage.Visible = false;
                }
                else
                {
                    lblPage.Visible = false;
                    btnPage.Visible = true;
                }

                if (pageNumber == 0)
                {
                    btnPage.Visible = false;
                    lblPage.Visible = false;
                }
                if ((count == 0 && pageNumber > 9) || (count == 11 && pageNumber == (Convert.ToInt32(CurrentPage / 10) * 10) + 11))
                {
                    btnPage.Text = "...";
                }

                count++;
            }

        }

        protected void drPages_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "getPage")
            {
                CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
                getdata();
            }
        }

    }
}